import { AfterViewChecked, Component, Injector, ViewChild, OnInit } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from 'shared/helpers/PrimengTableHelper';
import { UserServiceProxy, WorkflowServiceProxy, ProcessingContentApplyChangeMainDto, ProcessingContentApplyChangeStepUserDto, ProcessingContentApplyChangeDetailDto, ProcessingContentApplyChangeServiceServiceProxy, ProcessingContentApplyChangeInputDto } from '@shared/service-proxies/service-proxies';

import { SelectItem, SelectItemGroup } from 'primeng/api';
@Component({
  selector: 'ProcessingContentApplyChangeCreate',
  templateUrl: './ProcessingContentApplyChangeCreate.component.html',
  styleUrls: ['./ProcessingContentApplyChangeCreate.component.css']
})
export class ProcessingContentApplyChangeCreateComponent extends AppComponentBase implements OnInit {
  @ViewChild('createOrEditModal') modal: ModalDirective;
  @ViewChild('paginator') paginator: Paginator;
  @ViewChild('dataTable') dataTable: Table;
  @ViewChild('teskdataTable') teskdataTable: Table;
  // @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;
  filterText = '';
  selectedCar3: string;
  detailsprimengTableHelper: PrimengTableHelper;
  _processingContentApplyChangeDetailsDto: ProcessingContentApplyChangeDetailDto[];
  clonedOutsourcings: { [s: number]: ProcessingContentApplyChangeDetailDto; } = {};
  _processingContentApplyChangeMainDto: ProcessingContentApplyChangeMainDto = new ProcessingContentApplyChangeMainDto();
  stepusers: ProcessingContentApplyChangeStepUserDto;
  users: SelectItemGroup[];

  SupplierAyy: SelectItem[];

  selectProcessingContentApplyChangeDetailDto: ProcessingContentApplyChangeDetailDto[];
  index = 0;
  constructor(injector: Injector,
    private _processingContentApplyChangeService: ProcessingContentApplyChangeServiceServiceProxy,
    private _userService: UserServiceProxy,
    private _workflowService: WorkflowServiceProxy
  ) {
    super(injector);
    this.detailsprimengTableHelper = new PrimengTableHelper();
    this.stepusers = new ProcessingContentApplyChangeStepUserDto();
  }

  ngOnInit(): void {

    this.selectProcessingContentApplyChangeDetailDto = new Array<ProcessingContentApplyChangeDetailDto>();
    this._userService.getAllUserForDropDown().subscribe(resultdata => {
      console.log(resultdata);
      this.users = resultdata;
    });
  }

  show(): void {
    this.active = true;
    this.modal.show();
  }
  close(): void {
    this.active = false;
    this.modal.hide();
  }
  onShown(): void {

  }
  getTasks(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.paginator.changePage(0);
      return;
    }
    this.primengTableHelper.showLoadingIndicator();
    this._processingContentApplyChangeService.getProcessingContentFormChangeModelByCode(
      0,
      this.filterText,
      'Code',
      this.primengTableHelper.getMaxResultCount(this.paginator, event),
      this.primengTableHelper.getSkipCount(this.paginator, event)
    )
      .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
      .subscribe(result => {
        console.log(result);
        this.primengTableHelper.totalRecordsCount = result.totalCount;
        this.primengTableHelper.records = result.items;
        this.primengTableHelper.hideLoadingIndicator();
      });
  }

  //依据申请单获取任务
  SelectTask(record) {
    console.log(record);
    this._processingContentApplyChangeMainDto.applyUnit = record.applyUnit;
    let _supplier = record.supplierUnit.split(',');
    this.SupplierAyy = new Array();
    _.forEach(_supplier, viewItem => {
      console.log(viewItem);
      this.SupplierAyy.push({ label: viewItem, value: viewItem });
    });
    this._processingContentApplyChangeMainDto.supplierUnit = this.SupplierAyy[0].value;

    this._processingContentApplyChangeMainDto.code = record.code;
    this._processingContentApplyChangeService.getProcessingContentApplyChangeDetailByWorkFlowId(record.workflowId).subscribe(dto => {
      console.log(dto);
      this._processingContentApplyChangeDetailsDto = dto;
      this.detailsprimengTableHelper.totalRecordsCount = dto.length;
      this.detailsprimengTableHelper.records = dto;
      this.detailsprimengTableHelper.hideLoadingIndicator();
    });

    this._processingContentApplyChangeService.buildProcessingContentApplyChangeOrderCodeByOutsourcingCode(record.code).subscribe(code => {
      this._processingContentApplyChangeMainDto.changedCode = code;
    });
    this.index = 1;
  }

  handleChange(e) {
    this.index = e.index;
  }


  onRowEditInit(quotationmodel: ProcessingContentApplyChangeDetailDto) {
    console.log(quotationmodel);
    //quotationmodel.processingAmount = quotationmodel.outsouringAmount;
    this.clonedOutsourcings[quotationmodel.taskForModelId.toString()] = { ...quotationmodel };
  }

  onRowEditSave(quotationmodel: ProcessingContentApplyChangeDetailDto) {
    console.log(quotationmodel);
    if (!quotationmodel.workStatus) {
      this.notify.info('请填写原加工状态');
      return false;
    }
    if (!quotationmodel.changedWorkStatus) {
      this.notify.info('请填写变更后加工状态');
      return false;
    }
    if (!quotationmodel.changeRemark) {
      this.notify.info('请填写变更原因');
      return false;
    }
    if (!quotationmodel.currentOutsouringProgress) {
      this.notify.info('请填写当前外包产品进度');
      return false;
    }
    if (!quotationmodel.deliveryRate) {
      this.notify.info('请填写交付进度');
      return false;
    }
    if (quotationmodel.unitPrice <= 0) {
      this.notify.info('变更后参考单价必须大于0');
      return false;
    }
    delete this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];
    let _current = this._processingContentApplyChangeDetailsDto.find((element) => (element.taskForModelId == quotationmodel.taskForModelId));
    console.log(_current)
    if (_current === undefined) {
      quotationmodel.workStatus = quotationmodel.workStatus;
      quotationmodel.changedWorkStatus = quotationmodel.changedWorkStatus;
      quotationmodel.changeRemark = quotationmodel.changeRemark;
      quotationmodel.currentOutsouringProgress = quotationmodel.currentOutsouringProgress;
      quotationmodel.deliveryRate = quotationmodel.deliveryRate;
      quotationmodel.unitPrice = quotationmodel.unitPrice;
      quotationmodel.sumPrice = quotationmodel.unitPrice * quotationmodel.outsouringAmount; 
      this.selectProcessingContentApplyChangeDetailDto.push(quotationmodel);
    } else {
      _current.workStatus = quotationmodel.workStatus;
      _current.changedWorkStatus = quotationmodel.changedWorkStatus;
      _current.changeRemark = quotationmodel.changeRemark;
      _current.currentOutsouringProgress = quotationmodel.currentOutsouringProgress;
      _current.deliveryRate = quotationmodel.deliveryRate;
      _current.unitPrice = quotationmodel.unitPrice;
      _current.sumPrice = quotationmodel.unitPrice * quotationmodel.outsouringAmount;
      this.selectProcessingContentApplyChangeDetailDto.push(_current);
    }
    console.log(this.selectProcessingContentApplyChangeDetailDto)
  }

  onRowEditCancel(quotationmodel: ProcessingContentApplyChangeDetailDto, index: number) {
    console.log(this.clonedOutsourcings[quotationmodel.taskForModelId.toString()]);
    this._processingContentApplyChangeDetailsDto[index] = this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];
    delete this._processingContentApplyChangeDetailsDto[quotationmodel.taskForModelId];
  }

  save() {
    let input = new ProcessingContentApplyChangeInputDto();
    // tslint:disable-next-line: triple-equals

    input.workFlowName = '一般过程外包加工内容变更通知单';
    console.log(this.selectProcessingContentApplyChangeDetailDto);
    if (this.selectProcessingContentApplyChangeDetailDto.length === 0) {
      this.notify.info('请填写变更内容');
      this.saving = false;
      return;
    }

    //判断审批用户是否设置
    if (!this.stepusers.workshopManager) {
      this.notify.info('请选择申请单位经办人');
      this.saving = false;
      return;
    }
    if (!this.stepusers.workShopLeader) {
      this.notify.info('请选择申请单位主管领导');
      this.saving = false;
      return;
    }
    if (!this.stepusers.plannedProductionModelManager) {
      this.notify.info('请选择计划生产处型号主管');
      this.saving = false;
      return;
    }
    if (!this.stepusers.plannedProductionDirector) {
      this.notify.info('请选择计划生产处主管处长');
      this.saving = false;
      return;
    }

    input.stepUserDto = this.stepusers;
    input.processingContentApplyChangeMainDto = this._processingContentApplyChangeMainDto;
    input.processingContentApplyChangeDetailDtos = this.selectProcessingContentApplyChangeDetailDto;
    this.saving = true;

    console.log(input);
    this._processingContentApplyChangeService.createOrUpdateProcessingContentApplyChange(input)
      .pipe(finalize(() => { this.saving = false; }))
      .subscribe(() => {
        this.close();
      });
  }

}
